<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkAgent\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Utils\WeWorkFactory;
use MoChat\App\WorkAgent\Contract\WorkAgentContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use Psr\SimpleCache\CacheInterface;

/**
 * 企业应用 - 自建应用代开发授权二维码
 *
 * Class CustomizedAuthQRCode.
 * @Controller
 */
class CustomizedAuthQRCode extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkAgentContract
     */
    protected $workAgentService;

    /**
     * @Inject
     * @var WeWorkFactory
     */
    protected $weWorkFactory;

    /**
     * @Inject
     * @var CacheInterface
     */
    protected $cache;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/agent/customizedAuthQRCode", methods="get")
     */
    public function handle(): array
    {
        $user = user();

        $corpId = $user['corpIds'][0];
        $state = 'corpId' . $corpId;

        $templateId = config('framework.wework.app_template.id');
        if (empty($templateId)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未配置自建应用代开发模板ID');
        }

        $templateIdList = explode(',', $templateId);

        $data = [
            'state' => $state,
            'templateid_list' => $templateIdList,
        ];

        if ($url = $this->cache->get($this->getCacheKey($data))) {
            return [
                'url' => $url,
            ];
        }

        $wxResult = $this->weWorkFactory->getProviderApp()->provider->httpPostJson('/cgi-bin/service/get_customized_auth_url', $data);
        if ($wxResult['errcode'] !== 0) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, $wxResult['errmsg']);
        }

        $url = $wxResult['qrcode_url'];
        // 企业微信中为10天过期
        $this->cache->set($this->getCacheKey($data), $url, $wxResult['expires_in'] - 60 * 60 * 2);

        return [
            'url' => $url,
        ];
    }

    private function getCacheKey(array $data)
    {
        return sprintf('customizedAuthQRCode:v1:%s', md5(Json::encode($data)));
    }
}
